package com.ruoyi.web.controller.project;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.HttpMethod;
import com.ruoyi.project.domain.ProjectCategory;
import com.ruoyi.project.domain.ProjectColor;
import com.ruoyi.project.domain.ProjectTemplate;
import com.ruoyi.project.req.ProjectCategoryAddReq;
import com.ruoyi.project.req.ProjectCategoryReq;
import com.ruoyi.project.service.ProjectCategoryService;
import com.ruoyi.project.service.ProjectColorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.List;
import java.util.Objects;

/**
 * @author wjp
 * @date 2025年07月12日 13:43
 * @describe
 */
@RestController
@RequestMapping("/project/category")
@Api(tags = "项目分类管理")
@Slf4j
public class ProjectCategoryController extends BaseController {

    @Autowired
    private ProjectCategoryService projectCategoryService;

    @Autowired
    private ProjectColorService projectColorService;
    /**
     * 下载项目信息模板
     */
    @GetMapping("/download")
    @ApiOperation("下载项目模板文件")
    public ResponseEntity<byte[]> downloadTemplate() {
        // 指定模板文件路径（位于 resources/template 下）
        ClassPathResource resource = new ClassPathResource("template/项目划分呈现系统.xls");
        try (InputStream inputStream = resource.getInputStream()) {
            byte[] fileContent = IOUtils.toByteArray(inputStream);
            // 构建响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "project_template.xls");

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(fileContent);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
      * @User  wjp
      * @Time  2025/7/12
      * @param
      * @Return
      * @Description 导入项目分类
     */
    /**
     * 新增项目信息
     */
    @PreAuthorize("@ss.hasPermi('project:project:category:add')")
    @Log(title = "项目分类信息", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增项目分类")
    public AjaxResult add(@ApiParam("新增项目分类信息") @RequestBody @Valid ProjectCategoryAddReq projectCategory) {
        logger.info("新增项目分类信息入参：{}", projectCategory);
        return toAjax(projectCategoryService.add(projectCategory.getProjectCategory(),projectCategory.getProjectId(),getUsername(),getDeptId(),getUserId()));
    }

    /**
     * 修改项目分类信息
     */
    @PreAuthorize("@ss.hasPermi('project:project:category:edit')")
    @Log(title = "项目分类", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改项目")
    public AjaxResult edit(@ApiParam("修改项目信息") @RequestBody @Valid ProjectCategoryAddReq projectCategory) {
        logger.info("修改项目分类信息入参：{}", projectCategory);
        return toAjax(projectCategoryService.updateProjectCategory(projectCategory.getProjectCategory(), projectCategory.getProjectId(), getUsername(),getDeptId(),getUserId(),projectCategory.getIds()));
    }

    /**
     * 查询项目信息列表
     */
    @PreAuthorize("@ss.hasPermi('project:project:category:list')")
    @PostMapping("/list")
    @ApiOperation("查询项目列表") // 接口描述
    public AjaxResult list(@ApiParam("获取项目分类信息") @RequestBody @Valid ProjectCategoryReq req) {
        logger.info("获取项目分类入参:{}",req);
        List<ProjectCategory> projectCategory1 = projectCategoryService.listAll(req);
        logger.info("获取项目分类返回值:{}",projectCategory1);
        return AjaxResult.success(projectCategory1);
    }

    @GetMapping("/template/list")
    @ApiOperation(value = "获取项目模板树",httpMethod = "GET")
    public AjaxResult getTemplateList() {
        ProjectTemplate projectTemplate = projectCategoryService.getTree();
        logger.info("获取项目模板树返回值:{}",projectTemplate);
        return AjaxResult.success(projectTemplate);
    }

    @GetMapping("/color/config")
    @ApiOperation(value = "获取项目颜色配置",httpMethod = "GET")
    public AjaxResult getProjectColor() {
        ProjectColor projectColor = projectColorService.getProjectColor(getUserId());
        logger.info("获取项目颜色配置:{}",projectColor);
        return AjaxResult.success(projectColor);
    }

    @PostMapping("/color/addConfig")
    @ApiOperation(value = "项目颜色配置",httpMethod = "POST")
    public AjaxResult addProjectColor(@ApiParam("添加项目颜色配置") @RequestBody @Valid ProjectColor req) {
        logger.info("新增项目颜色配置:{}",req);
        if(Objects.isNull(req.getId())){
            req.setUserId(getUserId());
            req.setDeptId( getDeptId());
        }
        projectColorService.addProjectColor(req);

        return AjaxResult.success();
    }

}
